package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;

import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.pojo.Comment;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class CommentApiImpl implements CommentApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<Comment> queryCommentList(String publishId, Integer page, Integer pagesize, String sortProp, String sortOrder) {
        PageRequest pageRequest;
        //判断顺序还是倒序排列
        if ("ascending".equals(sortOrder)) {
            pageRequest = PageRequest.of(page - 1, pagesize, Sort.by(Sort.Order.asc(sortProp)));//顺序排序
        } else {
            pageRequest = PageRequest.of(page - 1, pagesize, Sort.by(Sort.Order.desc(sortProp)));//倒序排序

        }

        //设置查询条件,指定查询的id , 查询类型:评论
        Query query = new Query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.COMMENT.getType())).with(pageRequest);
        //执行查询 获取结果集合
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        return commentList;
    }
}
